const gameBoard = document.getElementById('game-board');
const boardSize = 20;
const snake = [{ x: 10, y: 10 }];
let food = { x: 15, y: 15 };
let direction = { x: 0, y: 0 };
let score = 0;

function createBoard() {
    for (let i = 0; i < boardSize * boardSize; i++) {
        const cell = document.createElement('div');
        cell.classList.add('cell');
        gameBoard.appendChild(cell);
    }
}

function drawSnake() {
    snake.forEach(segment => {
        const cell = document.querySelector(`.cell:nth-child(${segment.y * boardSize + segment.x + 1})`);
        cell.classList.add('snake');
    });
}

function drawFood() {
    const cell = document.querySelector(`.cell:nth-child(${food.y * boardSize + food.x + 1})`);
    cell.classList.add('food');
}

function update() {
    gameBoard.querySelectorAll('.cell').forEach(cell => cell.className = 'cell');
    moveSnake();
    drawSnake();
    drawFood();
    checkCollision();
}

function moveSnake() {
    const head = { x: snake[0].x + direction.x, y: snake[0].y + direction.y };
    snake.unshift(head);

    if (head.x === food.x && head.y === food.y) {
        score++;
        food = {
            x: Math.floor(Math.random() * boardSize),
            y: Math.floor(Math.random() * boardSize)
        };
    } else {
        snake.pop();
    }
}

function checkCollision() {
    const head = snake[0];
    if (head.x < 0 || head.x >= boardSize || head.y < 0 || head.y >= boardSize || snake.slice(1).some(segment => segment.x === head.x && segment.y === head.y)) {
        alert(`游戏结束，你的得分是: ${score}`);
        document.location.reload();
    }
}

document.addEventListener('keydown', event => {
    switch (event.key) {
        case 'ArrowUp':
            if (direction.y === 0) direction = { x: 0, y: -1 };
            break;
        case 'ArrowDown':
            if (direction.y === 0) direction = { x: 0, y: 1 };
            break;
        case 'ArrowLeft':
            if (direction.x === 0) direction = { x: -1, y: 0 };
            break;
        case 'ArrowRight':
            if (direction.x === 0) direction = { x: 1, y: 0 };
            break;
    }
});

createBoard();
drawSnake();
drawFood();
setInterval(update, 200);